package operator;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * 根据Process Time划分窗口
 * 底层调用WindowALL方法
 */
public class ProcessingTimeTumblingWindowDemo {

    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);
        // 设置窗口时间
        // env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);


        SingleOutputStreamOperator<Integer> nums = lines.map(Integer::parseInt);

        // 根据时间划分窗口 5 秒
        // AllWindowedStream<Integer, TimeWindow> window = nums.timeWindowAll(Time.seconds(5));
        // 使用底层API
        AllWindowedStream<Integer, TimeWindow> window = nums.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)));

        SingleOutputStreamOperator<Integer> sumed = window.sum(0);

        sumed.print();

        env.execute();
    }
}
